package com.example.myapplication.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.View

class TqView : View {
    private val paintOne = Paint()
    private val paintTwo = Paint()
    private val textPaint = Paint()
    private val dataPoints =
        floatArrayOf(
            20f, 50f, 30f, 80f, 60f, 40f
        )
    // 模拟的数据点

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init()
    }

    private fun init() {
        paintOne.color = Color.RED
        paintOne.style = Paint.Style.FILL
        paintTwo.color = Color.rgb(255, 152, 0)
        paintTwo.style = Paint.Style.FILL
        textPaint.color = Color.DKGRAY
        textPaint.textSize = 30f

    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val width = width.toFloat()
        val height = height.toFloat()
//        Log.d("TAG", "onDraw: ${height}+${width}")

        val horizontalInterval = width / (dataPoints.size - 1)
        val maxDataValue = dataPoints.maxOrNull() ?: 0
        val verticalInterval = height / maxDataValue.toFloat()
        var startX = 0f
        var startY = height - dataPoints[0] * verticalInterval
        for (i in 1 until dataPoints.size) {
            val endX = i * horizontalInterval
            val endY = height - dataPoints[i] * verticalInterval
            canvas.drawLine(startX, startY, endX, endY, paintTwo)
            startX = endX
            startY = endY
        }
        for ((index, dataPoint) in dataPoints.withIndex()) {
            val x = index * horizontalInterval
            val y = height - dataPoint * verticalInterval
            canvas.drawCircle(x, y, 8f, paintTwo)
            canvas.drawText(dataPoint.toInt().toString() + "°", x, y - 20, textPaint)
        }
    }

}